import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { BehaviorSubject } from "rxjs/BehaviorSubject";

import { TableTab, TableHeader } from "../f10-shared/interface-shared";
import { scroll } from "../f10-shared/common-methods";
import { compare, chartColors, removeHMS } from "../f10-shared/util";
import { F10Service } from "../service/f10.service";
import { ScrollService } from "../service/scroll.service";

@Component({
  templateUrl: 'share.component.html',
  styleUrls: ['share.component.less']
})

export class ShareComponent implements OnInit {
  timer = null;
  tabClicked = {
    flag: false
  };
  activeTabIndex = 0;
  scrollTimer = null;
  mustChange = false;
  subLists: TableTab[] = [
    {
      label: "股本结构",
      class: 'sub-title-0'
    },
    {
      label: "限售解禁",
      class: 'sub-title-1'
    }
  ]

  // 股票代码Observable
  routerParamsStream: Observable<any>;
  // 股本结构
  sharestructData: Observable<any>;
  sharestructHeader: TableHeader[] = [
    {
      format: false,
      label: `日期`,
      key: 'endDate',
      clickEmitter: true
    },
    {
      format: true,
      label: `总股本(股)`,
      key: 'totalShares'
    },
    {
      format: true,
      label: `流通股份(股)`,
      key: 'floatShare'
    },
    {
      format: true,
      label: `已上市流通A股(包含高管股)(股)`,
      key: 'AFloatListed'
    },
    {
      format: true,
      label: `有限售条件的流通股(股)`,
      key: 'restrictedShares'
    },
    {
      format: true,
      label: `未流通股(股)`,
      key: 'nonFloatShares'
    },
    {
      format: false,
      label: `股本变动原因说明`,
      key: 'changeReason'
    }
  ]

  // doughnut data
  doughnutData: Observable<any>;
  countDate: string;

  // 限售解禁
  unfreezeStockData: Observable<any>;
  unfreezeStockHeader: TableHeader[] = [
    {
      format: false,
      label: `解禁日期`,
      key: 'startDateForFloating'
    },
    {
      format: true,
      label: `解禁股份数(股)`,
      key: 'newMarketableAShares'
    },
    {
      format: true,
      label: `解禁股占总股本比例(%)`,
      key: 'proportion1'
    },
    {
      format: false,
      label: `解禁股份类型`,
      key: 'sourceType'
    }
  ]

  doughnutChartEmitter = new BehaviorSubject(null);
  tdClickedKey: string;
  constructor (
    private router: ActivatedRoute,
    private f10Service: F10Service,
    private scrollService: ScrollService
  ) {}

  ngOnInit () {
    // 获取股票代码
    this.routerParamsStream = this.router.parent.parent.params.map(params => params["id"]).filter(id => !!id).map(id => {
      let stock = {
        symbol: (<string>id).replace("_", ".")
      };
      return stock
    })

    // 股本结构
    this.sharestructData = this.routerParamsStream
      .switchMap(stock => this.getSharestructData(stock.symbol))
      .map(data => data.sort(compare('endDate', 'des')))
      .map(data => {
        let time = data.length > 0 ? data[0].endDate : null
        this.toggleChart(time)
        return data
      })
      .publish().refCount();

    // 图形数据
    this.doughnutData = this.sharestructData
      .switchMap(data => {
        return this.doughnutChartEmitter
          .distinctUntilChanged()
          .map(time => {
            if (time) {
              return data.filter(d => d.endDate === time)[0]
            } else {
              return data[0]
            }
          })
      })
      // => 此处没有无限售股字段 ===>>>> 领导要求自己计算，方法： 总股本 - 限售股
      .map(data => (data && {
        ...data,
        infiniteShares: data.totalShares - data.restrictedShares - data.nonFloatShares
      }))
      .map(data => (data && {
        ...data,
        infiniteShares: data.infiniteShares > 0 ? Math.floor(data.infiniteShares / 10000) : 0,
        restrictedShares: data.restrictedShares > 0 ? Math.floor(data.restrictedShares / 10000) : 0,
        nonFloatShares: data.nonFloatShares > 0 ? Math.floor(data.nonFloatShares / 10000) : 0
      }))
      .map(data => {
        return {
          type: 'doughnut',
          data: {
            labels: ['无限售股份(万股)', '限售股份(万股)', '未流通股份(万股)'],
            datasets: [{
              data: data ? [
                data.infiniteShares,
                data.restrictedShares,
                data.nonFloatShares
              ] : [],
              backgroundColor: [chartColors.red, chartColors.orange, chartColors.blue],
              label: '股本结构'
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            legend: {
              position: 'top',
            },
            title: {
              display: true,
              text: '日期：' + (data ? data.endDate : ''),
              padding: 7
            },
            animation: {
              animateScale: true,
              animateRotate: true
            }
          }
        }
      })

      this.unfreezeStockData = this.routerParamsStream
      .switchMap(stock => this.getUnfreezeStock(stock.symbol))
      .map(data => data.map(d => ({
        ...d,
        startDateForFloating: removeHMS(d.startDateForFloating)
      })))
  }

  tabToggle (event) {
    this.tabClicked.flag = true
    this.timer = scroll(`segment-container`, event, this.timer, this.tabClicked);
  }

  scrollEvent (e, el, el1, el2, el3, el4, el5) {
    if (this.scrollTimer) clearTimeout(this.scrollTimer)
    this.scrollTimer = setTimeout(() => {
      this.mustChange = !this.mustChange
      this.tabClicked.flag = false
      this.activeTabIndex = this.scrollService.tabIndex(e, el, el1, el2, el3, el4, el5)
    }, 50)
    if (this.tabClicked.flag) return
    this.activeTabIndex = this.scrollService.tabIndex(e, el, el1, el2, el3, el4, el5)
  }

  // 股本结构
  getSharestructData (symbol) {
    return this.f10Service.getSharestruct(symbol)
      .map(data => data.map((d, i) => ({
        ...d,
        endDate: d && d.endDate.slice(0, d.endDate.indexOf(' '))
      })))
  }

  // 限售解禁 => 预估限售条数不多此处固定为100
  getUnfreezeStock(symbol, page = 1, perPage = 100) {
    return this.f10Service.getUnfreezeStock({
        symbol: symbol,
        page: page,
        perPage: perPage
      })
  }

  // 切换图形数据
  toggleChart(time) {
    this.tdClickedKey = time
    this.doughnutChartEmitter.next(time)
  }
}